import json
import requests
import time
import os
import numpy as np
import math
from shapely.geometry import Polygon
from pyproj import Geod

def wgs84_to_gcj02(lng, lat):
    """
    WGS84 坐标系转 GCJ02 坐标系（火星坐标系）
    """
    PI = 3.1415926535897932384626
    ee = 0.00669342162296594323
    a = 6378245.0

    def transform_lat(x, y):
        ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x))
        ret += (20.0 * math.sin(6.0 * x * PI) + 20.0 * math.sin(2.0 * x * PI)) * 2.0 / 3.0
        ret += (20.0 * math.sin(y * PI) + 40.0 * math.sin(y / 3.0 * PI)) * 2.0 / 3.0
        ret += (160.0 * math.sin(y / 12.0 * PI) + 320 * math.sin(y * PI / 30.0)) * 2.0 / 3.0
        return ret

    def transform_lng(x, y):
        ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x))
        ret += (20.0 * math.sin(6.0 * x * PI) + 20.0 * math.sin(2.0 * x * PI)) * 2.0 / 3.0
        ret += (20.0 * math.sin(x * PI) + 40.0 * math.sin(x / 3.0 * PI)) * 2.0 / 3.0
        ret += (150.0 * math.sin(x / 12.0 * PI) + 300.0 * math.sin(x / 30.0 * PI)) * 2.0 / 3.0
        return ret

    if out_of_china(lng, lat):
        return lng, lat

    d_lat = transform_lat(lng - 105.0, lat - 35.0)
    d_lng = transform_lng(lng - 105.0, lat - 35.0)
    rad_lat = lat / 180.0 * PI
    magic = math.sin(rad_lat)
    magic = 1 - ee * magic * magic
    sqrt_magic = math.sqrt(magic)
    d_lat = (d_lat * 180.0) / ((a * (1 - ee)) / (magic * sqrt_magic) * PI)
    d_lng = (d_lng * 180.0) / (a / sqrt_magic * math.cos(rad_lat) * PI)
    
    return lng + d_lng, lat + d_lat

def out_of_china(lng, lat):
    """
    判断坐标是否在中国境外
    """
    return not (72.004 <= lng <= 137.8347 and 0.8293 <= lat <= 55.8271)

# 添加计算面积的函数
def calculate_area(coordinates):
    """
    计算多边形面积（平方米）
    coordinates: GeoJSON 格式的多边形坐标
    """
    # 提取多边形坐标
    polygon_coords = coordinates[0]  # 取外环坐标
    
    # 创建 Shapely 多边形对象
    polygon = Polygon(polygon_coords)
    
    # 计算大地测量面积（WGS84椭球体）
    geod = Geod(ellps='WGS84')
    area = abs(geod.geometry_area_perimeter(polygon)[0])
    
    return area

def calculate_centroid(coordinates):
    """
    计算多边形的中心点
    """
    # 提取所有顶点坐标
    vertices = coordinates[0]  # 取外环坐标
    # 转换为numpy数组便于计算
    vertices = np.array(vertices)
    # 计算中心点
    centroid = vertices.mean(axis=0)
    return centroid.tolist()

def read_geojson_and_geocode():
    """
    读取 GeoJSON 文件并对每个要素进行地理编码
    """
    try:
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        geojson_path = os.path.join(current_dir, 'geojson', 'result0323.geojson')
        
        # 读取 GeoJSON 文件
        with open(geojson_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        

        
        results = []
        # 遍历每个要素
        for feature in data['features']:
            # 获取第一个坐标点（根据几何类型处理）
            geometry = feature['geometry']
            if geometry['type'] == 'Polygon':
                # 计算多边形的中心点
                centroid = calculate_centroid(geometry['coordinates'])
                coordinates = geometry['coordinates'][0][0]  # 第一个点用于地理编码
                # 计算面积
                area = calculate_area(geometry['coordinates'])
            elif geometry['type'] == 'Point':
                centroid = geometry['coordinates']
                coordinates = centroid
                area = 0  # 点没有面积
            else:
                print(f"不支持的几何类型: {geometry['type']}")
                continue
            
            


            geojson = {
                "type": "FeatureCollection",
                "features": [feature]
            }
            geojson_str = json.dumps(geojson).replace('"', '\"')
            data = {
                "flight_date": "2025-03-23",
                "area": round(area, 2),
                "project_name": "fenghuang",
                "x": str(centroid[0]),  # 使用中心点坐标
                "y": str(centroid[1]),  # 使用中心点坐标
                "geojson": geojson_str,
                "task_id":"3104602d-5676-456b-b9db-be525ce1c485",
                "pre_task_id":"527c50b7-857d-417a-be78-b7c426aea64f"
            }
            results.append(data)

        results_str=json.dumps(results)
        print("\n处理完成！", len(results))
        print("\n处理完成: {results_str}")
        # 打印结果
        # for result in results:
        #     print(result)

        # 调用接口 
        url = "http://10.101.176.137:8081/sikong/data/waylinetask/aipushresults/saveBatch"
        # url = "https://www.xunjikejiai.site/sikong/data/waylinetask/aipushresults/saveBatch"
        headers = {
            "Content-Type": "application/json"
        }
        # 参数 results
        response = requests.post(url, headers=headers, data=results_str)



        # 返回结果
        return results
        
    except Exception as e:
        print(f"程序执行出错: {str(e)}")
        return None

if __name__ == '__main__':
    results = read_geojson_and_geocode()
